package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Email;

import java.io.Serializable;

public class EmailService implements Serializable {
    private BlockingQueue<Email> queue;
    private Boolean stopped = false;

    public EmailService() {
        queue = new BlockingQueue<Email>();
        Thread thread = new Thread(new EmailRoutine());
        thread.start();
    }

    public void sendNotificationEmail(Email email) {
        if (!stopped) {
            queue.add(email);
        } else {
            System.err.println("Sending email is stopped");
        }
    }

    public void close() {
        queue.close();
        stopped = true;
    }

    private class EmailRoutine implements Runnable {
        public void run() {

            while (!Thread.interrupted() && !stopped) {
                Email toSend;
                try {
                    toSend = queue.get();
                } catch (InterruptedException e) {
                    continue;
                }
                if (toSend != null) {
                    //send email here
                    System.out.println(toSend);
                }
            }
        }
    }

}